package com.asia.order.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.asia.order.utils.SignAlgorithmEnum.MD5;;

public class Signature {

	 public static String getSignContent(Map<String, String> map) {
        ArrayList<String> list = new ArrayList<String>();
        for(Map.Entry<String,String> entry:map.entrySet()){
            if(null!=entry.getValue()
                    && !"".equals(entry.getValue())
                    && !"sign".equals(entry.getKey())
                    //&& !"sign_type".equals(entry.getKey())
                    && !"key".equals(entry.getKey())){
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        return result.substring(0,result.length()-1);
    }




    //签名方法
    public static String getSign(SignAlgorithmEnum signType,Map<String, String> map, String key){
        String result = getSignContent(map);
        result += "&key=" +key;
//        System.out.println("Sign Before "+signType.name()+":" + result);
        result = SignAlgorithm.signByAlgorithm(signType,result,true);
//        System.out.println("Sign Result:" + result);
        return result;
    }

    //验证签名
    public static boolean checkSign(SignAlgorithmEnum signType,Map<String,String> map, String key) {
        String signOrginal = convertNull(map.get("sign")).toUpperCase();
        String signNow = getSign(signType,map,key);
        return signOrginal.equals(signNow);
    }


//    //RSA验证签名
//    public static boolean rsaCheck(SignAlgorithmEnum signType,Map<String, String> params,
//                                   String publicKey, String charset) {
//        String sign = params.get("sign");
//        String content = getSignContent(params);
//        return rsaCheckContent(signType,content, sign, publicKey, charset);
//    }



//    public static boolean rsaCheckContent(SignAlgorithmEnum signType,String content, String sign,
//                                          String publicKey, String charset) {
//        try {
//            PublicKey pubKey = getPublicKeyFromX509("RSA", publicKey);
//            String algorithms = "";
//            if(signType == RSA){
//                algorithms = "SHA1WithRSA";
//            } else if(signType == RSA2){
//                algorithms = "SHA256WithRSA";
//            }
//            java.security.Signature signature = java.security.Signature
//                    .getInstance(algorithms);
//            signature.initVerify(pubKey);
//            if (StringUtils.isEmpty(charset)) {
//                signature.update(content.getBytes());
//            } else {
//                signature.update(content.getBytes(charset));
//            }
//            return signature.verify(Base64.decode(sign));
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//    }

//    public static PublicKey getPublicKeyFromX509(String algorithm,
//                                                 String publicKey) throws Exception {
//        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
//
//        byte[] encodedKey = Base64.decode(publicKey);
//
//        return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
//    }

    // 过滤空值
    public static String convertNull(Object objData) {
        String returnValue = "";
        if (objData == null)
            return returnValue;
        try {
            returnValue = objData.toString();
            returnValue = (returnValue.toLowerCase().equals("null")) ? ""
                    : returnValue;
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = "";
        }
        return returnValue;
    }

    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String, String>();
        map.put("payUserSerial","20181227001");
        map.put("payUserId","1");
        map.put("totalFee","1");
        map.put("staffId","1");
        map.put("orgId","1");
        map.put("regionId","1");
        map.put("notifyUrl","http://www.baidu.com");
        map.put("frontUrl","http://www.baidu.com");
        map.put("commodityName","测试商品");
        map.put("commodityDesc","测试商品描述");
        map.put("signType","MD5");
        String sign = getSign(MD5,map,"8d731263-04d0-11e9-9827-7ce9d3f313fc");
        map.put("sign", sign);
        boolean checkResult = checkSign(MD5, map, "8d731263-04d0-11e9-9827-7ce9d3f313fc");
        System.out.println(checkResult);
    }

}